from django.db import connection

from app.service import order
from libs import common


def clean_retained_order():
    with connection.cursor() as cursor:
        ts = common.get_ts() - 86400
        sql = 'delete from cs_carts where `status` in (-1, 0) and created<=%s'
        cursor.execute(sql, [ts])


# 恢复支付失败的库存
def recover_pay_failed_order():
    ts = common.get_ts()
    from_ts = ts - 86400
    with connection.cursor() as cursor:
        sql = 'SELECT o.id order_id, sl.id log_id' \
              ' FROM `cs_orders` o LEFT JOIN cs_stock_logs sl ON o.id=sl.`stock_order_id`' \
              ' AND sl.stock_typ IN (10, 14) WHERE o.`status`=-3 AND o.created>=%s' \
              ' AND sl.id IS NULL'
        cursor.execute(sql, [from_ts])
        rows = cursor.fetchall()
        for row in rows:
            cs_order_id = row[0]
            order.recover_stock_from_order(cursor, cs_order_id, 14)
            common.logger('recover order id', cs_order_id, 'stock')
